package de.bensoft.jrail.client.com;

import javafx.beans.property.BooleanProperty;
import javafx.beans.property.LongProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleLongProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;

import org.apache.log4j.Logger;

import de.bensoft.jrail.business.entity.DeflectorData;
import de.bensoft.jrail.business.entity.TrackplanSegment;
import de.bensoft.jrail.business.service.TrackplanService;
import de.bensoft.jrail.client.com.interfaces.LI100;

public class DeflectorInstance {
	
	private static final Logger LOG = Logger.getLogger(TrainInstance.class);
	
	private TrackplanService service;
	
	private DeflectorComunicator deflectorCommunicator;
		
	public TrackplanSegment trackplanSegment;
	public TrackplanSegment getTrackplanSegment() { return trackplanSegment; }

	private BooleanProperty straightProperty;
	public  BooleanProperty straightProperty() { return straightProperty; }
	
	private BooleanProperty invertProperty;
	public  BooleanProperty invertProperty() { return invertProperty; }
	
	
	private LongProperty addressProperty;
	public  LongProperty addressProperty() { return addressProperty; }
	
	
	public DeflectorInstance(final DeflectorComunicator deflectorCommunicator, TrackplanSegment trackplanSegment, TrackplanService service) {
		this.deflectorCommunicator = deflectorCommunicator;
		this.trackplanSegment 	   = trackplanSegment;
		this.service 			   = service;
		
		DeflectorData data = trackplanSegment.getDeflectorData();
		
		straightProperty = new SimpleBooleanProperty (data.getStraight());
		invertProperty   = new SimpleBooleanProperty (data.getInvert());
		addressProperty  = new SimpleLongProperty    (data.getAddress());
		
		straightProperty.addListener(new ChangeListener<Boolean>() {
			public void changed(ObservableValue<? extends Boolean> arg0, Boolean arg1, Boolean arg2) {
				onDeflectorSwitched();
			}		
		});
	}
	
	
	public void save() {

		trackplanSegment.getDeflectorData().setAddress  (addressProperty.get());
		trackplanSegment.getDeflectorData().setInvert   (invertProperty.get());
		trackplanSegment.getDeflectorData().setStraight (invertProperty.get());
		
		service.saveTrackplanSegment(trackplanSegment);
	}
	
	private void onDeflectorSwitched() {
		String to = "straight";
		if(!straightProperty.get())
			to = "curved";
		
		LOG.info("[" + addressProperty.get() + "] Deflector switched to " + to + "!");
		
		boolean toStraight = straightProperty.get();
		if(invertProperty.get())
			 toStraight = !straightProperty.get();
		
		byte[] cmd = LI100.buildSwitchCommand(addressProperty.get(), toStraight);
		deflectorCommunicator.sendCommand(cmd);
	}
}
